package com.zhx.sweet.controller;


import com.zhx.sweet.common.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理是否需要身份验证的controller
 *
 * @author zhx
 * @create 2017-11-02 10:50
 **/
@RestController
public class BrowserSecurityController {
    private  final static Logger logger = LoggerFactory.getLogger(BrowserSecurityController.class);

    //HttpSessionRequestCache spring 获取之前缓存的请求
    private RequestCache requestCache = new HttpSessionRequestCache();
    //用来做跳转的类
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    @RequestMapping("/v1/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ResponseEntity requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {

        SavedRequest saveRequest = requestCache.getRequest(request, response);

        if(saveRequest != null){
            String targetUrl = saveRequest.getRedirectUrl();

            logger.info("BrowserSecurityController 中 引发跳转的请求是:{}" ,targetUrl);
        }
        return  ResponseEntity.status(401).body("访问的请求需要身份认证,请引导用户到登录页");
    }


    @GetMapping("/session/invalid")
    @ResponseStatus(code=HttpStatus.UNAUTHORIZED)
    public ResponseEntity sessionInvalid(){
        String message="session过期";
        return  ResponseEntity.ok(message);
    }
}
